﻿/* Copyright (c) 2010 EPiServer AB
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
 * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System.Web.UI;
using EPiServer.Core;
using EPiServer.Web.WebControls;

namespace EPiServer.Municipality.Web.UI.WebControls {
    public class CustomPageTree : PageTree {

        /* *******************************************************************
        * Properties
        * *******************************************************************/
        #region public ITemplate ExpandableItemTemplate
        /// <summary>
        /// Get/Sets the ExpandableTemplate of the PageTree
        /// </summary>
        /// <value></value>
        [TemplateContainer(typeof(PageTemplateContainer))]
        public ITemplate ExpandableItemTemplate { get; set; }
        #endregion
        /* *******************************************************************
        * Methods
        * *******************************************************************/
        #region protected override void CreateChildControls()
        /// <summary>
        /// 
        /// </summary>
        protected override void CreateChildControls() {
            PageData page = PageReference.IsNullOrEmpty(RootLink) ? null : GetPage(RootLink);
            CreateTemplateControl(page, HeaderTemplate, 0, false);
            CreateItemsRecursive(1, string.Empty);
            CreateTemplateControl(page, FooterTemplate, 0, false);
        }
        #endregion
        #region private void CreateItemsRecursive(int level, string path)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="level"></param>
        /// <param name="path"></param>
        private void CreateItemsRecursive(int level, string path) {
            var enumerable = PageLoader.HierarchicalSelect(path);
            if ((enumerable.Pages.Count != 0) && !PageReference.IsNullOrEmpty(RootLink)) {
                var data = (path != string.Empty) ? ((PageHierarchyData)enumerable.GetParent()) : new PageHierarchyData(PageSource.GetPage(RootLink), PageLoader);
                CreateTemplateControl(data.Page, IndentTemplate, level, data.HasChildren);

                if (level == 1) {
                    var homeTemplate = new PageTemplateContainer(GetPage(PageReference.StartPage), 0, true);
                    CreateTemplateControl(data.Page, ItemHeaderTemplate, level, data.HasChildren);

                    if (CurrentPage.PageLink.CompareToIgnoreWorkID(PageReference.StartPage)) {
                        homeTemplate.InstantiateWithFallback(new[] { SelectedTopTemplate });
                    } else {
                        homeTemplate.InstantiateWithFallback(new[] { TopTemplate });
                    }
                    Controls.Add(homeTemplate);
                    CreateTemplateControl(data.Page, ItemFooterTemplate, level, data.HasChildren);
                }


                foreach (PageHierarchyData data2 in enumerable) {
                    var page = data2.Page;
                    CreateTemplateControl(page, ItemHeaderTemplate, data2.Indent, data2.HasChildren);
                    CreateItemTemplateControl(page, level, data2.HasChildren, (CurrentPage == null) ? PageReference.EmptyReference : CurrentPage.PageLink);
                    if ((data2.HasChildren && ((NumberOfLevels == -1) || (level < NumberOfLevels))) && IsExpanded(data2.Page.PageLink)) {
                        CreateItemsRecursive(level + 1, page.PageLink.ToString());
                    }
                    CreateTemplateControl(page, ItemFooterTemplate, level, data2.HasChildren);
                }
                CreateTemplateControl(data.Page, UnindentTemplate, level, data.HasChildren);
            }
        }
        #endregion
        #region private void CreateItemTemplateControl(PageData page, int level, bool hasChildren, PageReference currentPageLink)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <param name="level"></param>
        /// <param name="hasChildren"></param>
        /// <param name="currentPageLink"></param>
        private void CreateItemTemplateControl(PageData page, int level, bool hasChildren, PageReference currentPageLink) {
            var template = new PageTemplateContainer(page, level, hasChildren);
            if (level == 1) {
                if (page.PageLink.CompareToIgnoreWorkID(currentPageLink) && IsExpanded(page.PageLink)) {
                    InstantiateSelectedExpandedTopTemplate(template);
                } else if (IsExpanded(page.PageLink)) {
                    InstantiateExpandedTopTemplate(template);
                } else if (page.PageLink.CompareToIgnoreWorkID(currentPageLink)) {
                    InstantiateSelectedTopTemplate(template);
                } else {
                    InstantiateTopTemplate(template);
                }
            } else if (page.PageLink.CompareToIgnoreWorkID(currentPageLink) && IsExpanded(page.PageLink)) {
                InstantiateSelectedExpandedItemTemplate(template);
            } else if (IsExpanded(page.PageLink)) {
                InstantiateExpandedItemTemplate(template);
            } else if (page.PageLink.CompareToIgnoreWorkID(currentPageLink)) {
                InstantiateSelectedItemTemplate(template);
            } else if(hasChildren) {
                InstantiateExpandableItemTemplate(template);
            } else {
                InstantiateItemTemplate(template);
            }
            Controls.Add(template);
        }
        #endregion
        #region protected virtual void InstantiateExpandableItemTemplate(PageTemplateContainer template)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="template"></param>
        protected virtual void InstantiateExpandableItemTemplate(PageTemplateContainer template) {
            template.InstantiateWithFallback(new[] { ExpandableItemTemplate });
        }
        #endregion
    }
}